package com.atjg.autocat.mqtt;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.atjg.autocat.utils.DeviceUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.zhy.baselibrary.utils.Klog;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;

import java.util.HashMap;
import java.util.Map;

public class MQTTService extends Service {
    public static final String TAG = MQTTService.class.getSimpleName();
    private static MqttClient client;
    private IGetMessageCallBack IGetMessageCallBack;
    private MqttConnectOptions conOpt;
    private String userName = MqttConfig.TOPIC_NAME;
    private String passWord = "" + MqttConfig.TOPIC_CODE + "";

    private final MqttCallbackExtended MyMqttCallBack = new MqttCallbackExtended() {
        @Override
        public void connectionLost(Throwable throwable) {
            if (IGetMessageCallBack != null) {
                IGetMessageCallBack.setStatus("MQTT失败", throwable.toString());
            }
            Klog.Companion.d(TAG, "-------------MQTT失败-----------" + throwable.toString());

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Klog.Companion.d(TAG, "-------------MQTT收到信息-----------"+message.toString());
            if (MQTTService.this.IGetMessageCallBack != null) {
                MQTTService.this.IGetMessageCallBack.setMessage(topic, message);
            }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            Klog.Companion.d(TAG, "-------------MQTT发送完成-----------");
        }

        @Override
        public void connectComplete(boolean b, String s) {
            Klog.Companion.d(TAG, "-------------MQTT连接完成-----------");
            try {
                String zt = MqttConfig.TOPIC_ADDRESS + DeviceUtils.Companion.getDeviceId()+"/ctr";
                Klog.Companion.d("-----订阅主题事件-------", zt);
                MQTTService.client.subscribe(zt, 1);
                if (IGetMessageCallBack != null) {
                    IGetMessageCallBack.setStatus("连接完成并订阅成功", "SUCCESS");
                }
            } catch (MqttException e) {
                if (IGetMessageCallBack != null) {
                    IGetMessageCallBack.setStatus("MQTT订阅失败", e.getMessage());
                }
                e.printStackTrace();
            }
        }
    };


    @Override
    public void onCreate() throws IllegalArgumentException {
        super.onCreate();
        try {
            init();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    private void init() throws MqttException, IllegalArgumentException {
        Klog.Companion.d("-------------绑定客户端------------");
        String tmpDir = System.getProperty("java.io.tmpdir");
        new MqttDefaultFilePersistence(tmpDir);
        String clinetid = MqttConfig.MQTT_CLIENT_ID + "_" + (Math.random() * 9999.0d);
        client = new MqttClient(MqttConfig.MQTT_URL, clinetid, null);
        client.setCallback(this.MyMqttCallBack);
        this.conOpt = new MqttConnectOptions();
        this.conOpt.setCleanSession(false);
        this.conOpt.setConnectionTimeout(20);
        this.conOpt.setKeepAliveInterval(10);
        this.conOpt.setUserName(this.userName);
        this.conOpt.setPassword(this.passWord.toCharArray());
        this.conOpt.setAutomaticReconnect(true);
        doClientConnection();
    }

    @Override
    public void onDestroy() {
        stopSelf();
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    public static boolean isMqtttConnected() {
        MqttClient mqttClient = client;
        if (mqttClient != null) {
            return mqttClient.isConnected();
        }
        return false;
    }

    private void doClientConnection() {
        if (!client.isConnected() && isConnectIsNormal()) {
            try {
                Klog.Companion.d("----------------doClientConnection开始连结----------------");
                client.setCallback(this.MyMqttCallBack);
                client.connect(this.conOpt);
            } catch (MqttException e) {
                Klog.Companion.d("-----------MqttException:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private boolean isConnectIsNormal() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
            Log.i(TAG, "MQTT当前网络名称：" + name);
            return true;
        }
        Log.i(TAG, "MQTT 没有可用网络");
        return false;
    }
    public void publishMsg(String qrcode) {
        String deviceId = DeviceUtils.Companion.getDeviceId();
        Map<String,String> map =new HashMap<>();
        map.put("cmd", qrcode);
        map.put("DevId", DeviceUtils.Companion.getDeviceId());
       String content =  GsonUtils.toJson(map);
       Klog.Companion.d("------发送的消息体："+content);
        Klog.Companion.d("------事件："+"hs/server/xianxc/"+deviceId);
        //此处消息体需要传入byte数组
        MqttMessage message = new MqttMessage(content.getBytes());
        //设置质量级别
        message.setQos(0);
        try {
            if (isMqtttConnected()) {
                client.publish("hs/server/xianxc/"+deviceId, message);
            }
        } catch (MqttException e) {
            Klog.Companion.d(" publishException: " + e.getMessage());
        }
    }
    @Override // android.app.Service
    public IBinder onBind(Intent intent) {
        Log.e(getClass().getName(), "onBind");
        return new CustomBinder();
    }

    public void setIGetMessageCallBack(IGetMessageCallBack IGetMessageCallBack) {
        this.IGetMessageCallBack = IGetMessageCallBack;
    }

    public class CustomBinder extends Binder {
        public CustomBinder() {
        }

        public MQTTService getService() {
            return MQTTService.this;
        }
    }

}